
export function formatTime(time){
    if(time==null){
        return ""
    }
    let date = new Date(time);
    //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let y = date.getFullYear();
    let MM = date.getMonth() + 1;
    MM = MM < 10 ? ('0' + MM) : MM; //月补0
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d; //天补0
    let h = date.getHours();
    h = h < 10 ? ('0' + h) : h; //小时补0
    let m = date.getMinutes();
    m = m < 10 ? ('0' + m) : m; //分钟补0
    let s = date.getSeconds();
    s = s < 10 ? ('0' + s) : s; //秒补0
    return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
}

/**
 * @uses 根据生日计算年龄，年龄的格式是：2016-09-23
 * @param string birthday
 * @return string|number
 **/
export function getAge(birthday) {
    let iage = 0;
    if (birthday!=null && birthday!='') {
        //获取出生日期的年月日
        let year = getYmd(birthday,'y');
        let month = getYmd(birthday, 'm');
        let day = getYmd(birthday, 'd');

        //获取当前时间的年月日
        let myDate = new Date();
        let now_year = myDate.getFullYear();
        let now_month = myDate.getMonth()+1;
        let now_day = myDate.getDate();

        if (now_year > year) {
            iage = now_year - year - 1;
            if (now_month > month) {
                iage++;
            } else if (now_month == month) {
                if (now_day >= day) {
                    iage++;
                }
            }
        }
    }
    return iage;
}

/**
 * @uses 根据指定日期返回你年月日，日期格式是：2016-09-23
 * @param string s 日期字符串
 * @param string type 返回的 年y 月m 日d
 * @return string|number
 **/
function getYmd(s,type) {
    // var s = "2010-5-6";
    let a = s.split("-");
    if (a.length > 2) {
        let y = a[0];
        let m = a[1];
        let d = a[2];
        let returnStr = '';
        switch(type){
            case 'y':
                returnStr = y;
                break;
            case 'm':
                returnStr = m;
                break;
            case 'd':
                returnStr = d;
                break;
            default:
                returnStr = '';
                break;
        }
        return returnStr;
    }else{
        return '';
    }
}
